package com.atguigu.tingshu.order.pattern;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 抽象类，实现策略接口
 *
 * @author: atguigu
 * @create: 2025-06-17 09:32
 */
public abstract class AbstractTradeStrategy implements TradeStrategy {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成订单流水号
     * @return
     */
    public void generateTradeNo(OrderInfoVo orderInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        //5.3.2 流水号机制第一步：生成本次订单流水号，解决回退、重复点击提交造成订单重复提交问题
        //5.3.2.1. 构建当前用户本次订单流水号Key
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //5.3.2.2. 构建当前用户本次订单流水号UUID值
        String tradeNo = IdUtil.randomUUID();
        //5.3.2.3. 写入Redis有效时间5分钟
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
    }

    /**
     * 生成订单签名
     * @param orderInfoVo
     */
    public void generateSign(OrderInfoVo orderInfoVo) {
        //5.3.3.1. 生成本次订单时间戳
        long timeMillis = System.currentTimeMillis();
        orderInfoVo.setTimestamp(timeMillis);
        //5.3.3.2 将订单VO转为Map，生成本次订单签名值 TODO 由于付款方式属性payWay为null不需要参与签名
        Map<String, Object> orderInfoMap = BeanUtil.beanToMap(orderInfoVo, false, true);
        String sign = SignHelper.getSign(orderInfoMap);
        orderInfoVo.setSign(sign);
    }

}
